package net.xinqushi.socket.nio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author xjie 2019/7/17 14:11
 * @description  a blocked channelServer , 阻塞式的channelServer与ServerSocket 阻塞特性一致
 */
public class BlockServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        ByteBuffer buf = ByteBuffer.allocate(48);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while(true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            //do something with socketChannel...
            int readBytes = 0;
            while ( -1 != ( readBytes = socketChannel.read(buf)) ){
                bos.write(buf.array() , 0 , readBytes);
            }
            System.out.println(new String(bos.toByteArray()));

/*            String newData = "Server String to write to client..." + System.currentTimeMillis();
            buf.clear();//ready to put
            buf.put(newData.getBytes());
            buf.flip();//ready for read
            while(buf.hasRemaining()) {
                socketChannel.write(buf);//一次性写入buffer 2 channel
            }*/
            socketChannel.close();//标识end
        }

        //serverSocketChannel.close();

    }
}
